﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TestGoogleService : MonoBehaviour 
{
	[SerializeField]
	public BusInformationRequester requester;
	[SerializeField] 
	public SpriteRenderer spriteRenderer;


	void Start () 
	{
		
	}

	void OnGUI()
	{
		//if(TestBusService.loaded)
		//{
			if(GUI.Button(new Rect(10, 20, 100, 30), "312"))
			{
				StopAllCoroutines();
				StartCoroutine(UpdateMap(GenerateMarkersByLine("312")));
			}
			if(GUI.Button(new Rect(10, 60, 100, 30), "600"))
			{
				StopAllCoroutines();
				StartCoroutine(UpdateMap(GenerateMarkersByLine("600")));
			}
			if(GUI.Button(new Rect(10, 100, 100, 30), "601"))
			{
				StopAllCoroutines();
				StartCoroutine(UpdateMap(GenerateMarkersByLine("601")));
			}
			if(GUI.Button(new Rect(10, 140, 100, 30), "610"))
			{
				StopAllCoroutines();
				StartCoroutine(UpdateMap(GenerateMarkersByLine("610")));
			}
		//}
	}

	private string GenerateMarkersByLine(string line)
	{
		List<BusInformationModel> bus = requester.FilterByLine(line);
		
		string markers = "";
		if(bus.Count > 0)
		{
			markers = "&markers=color:red|label:B";
			for (int i = 0; i < bus.Count && i < 10; i++) 
			{
				markers += "|" + bus[i].latitude + "," + bus[i].longitude;
			}
		}

		return markers;
	}

	private IEnumerator UpdateMap(string markers)
	{
		string url = BuildPathUrl(TestManager.latitude, TestManager.longitude, markers);
		Debug.Log("Mapa url: " + url);

		WWW www = new WWW(url);
		yield return www;

		Texture2D tex = new Texture2D(640, 640);
		www.LoadImageIntoTexture(tex);

		spriteRenderer.sprite = 
			Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));

		www.Dispose();
	}

	private string BuildPathUrl(float myLatitude, float myLongitute, string markers)
	{
		return
			"http://maps.googleapis.com/maps/api/staticmap?" +
			"center=" + myLatitude+","+myLongitute + "&" +
			"zoom=12" + "&" +
			"size=640x640" + "&" +
			"sensor=false" +
			markers;
	}
}
